package com.infoland.afanmall.model.youXuan.adapter;

import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.ToxicBakery.viewpager.transforms.DefaultTransformer;
import com.alibaba.fastjson.JSONObject;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.infoland.afanmall.R;
import com.infoland.afanmall.base.util.CONST;
import com.infoland.afanmall.base.util.CacheKit;
import com.infoland.afanmall.base.util.LogKit;
import com.infoland.afanmall.base.util.ToolsKit;
import com.infoland.afanmall.base.util.banner.HolderCreator;
import com.infoland.afanmall.base.util.layoutManager.GridSpacingItemDecoration;
import com.infoland.afanmall.base.util.okhttp.OkHttpKit;
import com.infoland.afanmall.model.youXuan.entity.BannerEntity;
import com.infoland.afanmall.model.youXuan.entity.OptionEntity;
import com.infoland.afanmall.model.youXuan.entity.PtParaEntity;
import com.infoland.afanmall.model.youXuan.entity.PtResponse;
import com.infoland.afanmall.model.youXuan.entity.TimeByEntity;
import com.infoland.afanmall.model.youXuan.entity.YouXuanType;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.wang.avi.AVLoadingIndicatorView;

import java.util.ArrayList;
import java.util.List;

public class YouXuanAdapter extends BaseMultiItemQuickAdapter<MultiItemEntity, BaseViewHolder> {
    private RadioButton pt_bt_zh;
    private RadioButton pt_bt_xl;
    private RadioButton pt_bt_jg;
    private RadioButton pt_bt_zx;
    //
    private int layoutPosition = 0;
    private Context context;
    private FragmentActivity activity;
    private OptionAdapter optionAdapter;
    private RadioGroup radioGroup;
    private PtAdapter ptAdapter;
    private List<MultiItemEntity> data;
    private AVLoadingIndicatorView avi_pt;
    private RecyclerView ptRecl;
    private RecyclerView baseRecl;
    private LinearLayoutManager baseLayoutManager;
    private SmartRefreshLayout refreshLayout;
    private LinearLayout toolbar;
    private NestedScrollView net_scro;
    //
    int pageNumber;
    int pageSize;
    boolean lastPage = false;
    PtParaEntity ptParaEntity = null;

    public YouXuanAdapter(Context context, List<MultiItemEntity> data, FragmentActivity activity,
                          RecyclerView mRecyclerView, LinearLayoutManager linearLayoutManager,
                          SmartRefreshLayout smartRefreshLayout, LinearLayout ll_toolbar) {
        super(data);
        this.context = context;
        this.activity = activity;
        this.data = data;
        this.baseRecl = mRecyclerView;
        this.baseLayoutManager = linearLayoutManager;
        this.refreshLayout = smartRefreshLayout;
        this.toolbar = ll_toolbar;
        addItemType(YouXuanType.BANNER, R.layout.you_xuan_banner);
        addItemType(YouXuanType.OPTION, R.layout.you_xuan_option);
        addItemType(YouXuanType.TIME_BY, R.layout.you_xuan_time_by);
        addItemType(YouXuanType.PT, R.layout.you_xuan_pt);
    }

    @Override
    protected void convert(BaseViewHolder holder, MultiItemEntity item) {
        switch (holder.getItemViewType()) {
            /*** 滑动页 **/
            case YouXuanType.BANNER:
                setBanner(holder, item);
                break;
            /*** 八个圆钮 **/
            case YouXuanType.OPTION:
                initOption(holder, item);
                break;
            /*** 抢购 爆款*/
            case YouXuanType.TIME_BY:
                initTimePay(holder, item);
                break;
            /***普通商品*/
            case YouXuanType.PT:
                initPT(holder, item);
                break;
            default:
                break;
        }
    }

    //    /***普通商品*/
    private void initPT(BaseViewHolder holder, MultiItemEntity item) {
        Log.e(TAG, "TYPE_TWO  " + YouXuanType.PT);
        layoutPosition = holder.getLayoutPosition();
        ptRecl = holder.getView(R.id.pt_recl);
        radioGroup = holder.getView(R.id.rg_main);
        radioGroup.check(R.id.pt_bt_zh);
        avi_pt = holder.getView(R.id.avi_pt);
        setRefreshLayout();
        GridLayoutManager gridLayoutManager = new GridLayoutManager(context, 2);
        ptAdapter = new PtAdapter(((PtResponse) item).getList(), context, activity);
        ptAdapter.setPtLinster((holder1, itemType, position, item1, item_type) -> {
            youXuanLinster.onClick(holder1, itemType, position, item1, item_type);
        });
        ptRecl.setLayoutManager(gridLayoutManager);
        ptRecl.addItemDecoration(new GridSpacingItemDecoration(2, SizeUtils.dp2px(10), true));
        ptRecl.setAdapter(ptAdapter);
        RadioButton jiage = holder.getView(R.id.pt_bt_jg);
        pt_bt_zh.setOnClickListener(v -> {
            ToolsKit.setSleep500(pt_bt_zh);
            RadioButton radioButton = holder.getView(R.id.pt_bt_zh);
            radioButton.setChecked(true);
            clickZH(pt_bt_zh.isChecked(), pt_bt_zh, jiage);

        });
        pt_bt_zx.setOnClickListener(v -> {
            RadioButton radioButton = holder.getView(R.id.pt_bt_zx);
            ToolsKit.setSleep500(pt_bt_zx);
            radioButton.setChecked(true);
            clickZX(pt_bt_zx.isChecked(), pt_bt_zx, jiage);
        });
        pt_bt_xl.setOnClickListener(v -> {
            ToolsKit.setSleep500(pt_bt_xl);
            RadioButton radioButton = holder.getView(R.id.pt_bt_xl);
            radioButton.setChecked(true);
            clickXL(pt_bt_xl.isChecked(), pt_bt_xl, jiage);

        });
        pt_bt_jg.setOnClickListener(v -> {
            ToolsKit.setSleep500(pt_bt_jg);
            RadioButton radioButton = holder.getView(R.id.pt_bt_jg);
            radioButton.setChecked(true);
            clickJG(pt_bt_jg.isChecked(), pt_bt_jg, jiage);
        });

        holder.getView(R.id.pt_bt_zh).setOnClickListener(v -> {
            ToolsKit.setSleep500(holder.getView(R.id.pt_bt_zh));
            this.pt_bt_zh.setChecked(true);
            clickZH(((RadioButton) holder.getView(R.id.pt_bt_zh)).isChecked(), holder.getView(R.id.pt_bt_zh), jiage);
        });
        holder.getView(R.id.pt_bt_xl).setOnClickListener(v -> {
            ToolsKit.setSleep500(holder.getView(R.id.pt_bt_xl));

            this.pt_bt_xl.setChecked(true);
            clickXL(((RadioButton) holder.getView(R.id.pt_bt_xl)).isChecked(), holder.getView(R.id.pt_bt_xl), jiage);
        });
        holder.getView(R.id.pt_bt_jg).setOnClickListener(v -> {
            ToolsKit.setSleep500(holder.getView(R.id.pt_bt_jg));
            this.pt_bt_jg.setChecked(true);
            clickJG(((RadioButton) holder.getView(R.id.pt_bt_jg)).isChecked(), holder.getView(R.id.pt_bt_jg), jiage);
        });
        holder.getView(R.id.pt_bt_zx).setOnClickListener(v -> {
            ToolsKit.setSleep500(holder.getView(R.id.pt_bt_zx));
            this.pt_bt_zx.setChecked(true);
            clickZX(((RadioButton) holder.getView(R.id.pt_bt_zx)).isChecked(), holder.getView(R.id.pt_bt_zx), jiage);
        });
//        adapters.add(ptAdapter);
    }

    //    /*** 爆款*/
    private void initTimePay(BaseViewHolder holder, MultiItemEntity item) {
        Log.e(TAG, "TYPE_Qiang_Gou  " + YouXuanType.TIME_BY);
        RecyclerView timeByRel = holder.getView(R.id.qianggou_rel);
        timeByRel.setLayoutManager(new LinearLayoutManager(context));
        TimeByEntity entity = (TimeByEntity) item;
        TimeByAdapter timeByAdapter = new TimeByAdapter(R.layout.you_xuan_time_by_item, entity.getList(), context, activity);
        timeByAdapter.setBKLinster((holder1, itemType, position, item_bk, item_type) -> {
            youXuanLinster.onClick(holder1, itemType, position, item_bk, item_type);
        });
        timeByRel.setAdapter(timeByAdapter);
    }

    //    /*** 八个圆钮 **/
    private void initOption(BaseViewHolder holder, MultiItemEntity item) {
        Log.e(TAG, "TYPE_TWO  " + YouXuanType.OPTION);
        OptionEntity optionEntity = (OptionEntity) item;
        /***获取数据*/
        RecyclerView optionRecl = holder.getView(R.id.youxuan_two_rel);
        GridLayoutManager layoutManage = new GridLayoutManager(context, 4);
        optionRecl.setLayoutManager(layoutManage);
        optionAdapter = new OptionAdapter(R.layout.item_option_item, optionEntity.list, context, activity);
        optionAdapter.setOnItemClickListener((adapter, view, position) -> {
            youXuanLinster.onClick(holder, YouXuanType.OPTION, position, optionEntity.list.get(position), "");
        });
        optionRecl.setAdapter(optionAdapter);
    }

    //    /*** 滑动页 **/
    private void setBanner(BaseViewHolder holder, MultiItemEntity item) {
        Log.e(TAG, "TYPE_BANNER   " + YouXuanType.BANNER);
        BannerEntity bannerEntity = (BannerEntity) item;
        List<String> images = new ArrayList<>();
        List<String> names = new ArrayList<>();
        List<String> contents = new ArrayList<>();
        for (BannerEntity entity : bannerEntity.list) {
            LogKit.E(" entity  ", "  " + entity.toString());
            images.add(entity.getF_url());
            names.add(entity.getAd_name());
//            contents.add(entity.getde);
        }
        ConvenientBanner<String> mBanner = holder.getView(R.id.youxuan_banner);
        mBanner.setOnItemClickListener((position) -> {
            youXuanLinster.onClick(holder, YouXuanType.BANNER, position, bannerEntity.list.get(position), "");
        });
        mBanner.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                holder.setText(R.id.banner_title, names.get(position));
                holder.setText(R.id.banner_content, "");
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        setBanner(mBanner, images);
        holder.setText(R.id.banner_title, names.get(0));
        holder.setText(R.id.banner_content, "");
    }

    //    /*** 设置Banner*/
    private void setBanner(ConvenientBanner<String> mBanner, List<String> images) {
        mBanner.setPages(new HolderCreator(), images)
//                .setPageIndicator(new int[]{R.drawable.dot_normal, R.drawable.dot_focus})
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                .setPageTransformer(new DefaultTransformer())
                .startTurning(3000)
                .setCanLoop(true);
    }

    //    /***设置滑动监听*/
    private void setRefreshLayout() {
        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            loadPtData();
        });
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            refrePtData();
        });
    }


    //点击综合
    private void clickZH(boolean checked, RadioButton view, RadioButton jiage) {
        ToolsKit.setRadioDrawableRight(jiage, R.mipmap.jiagemoren);
        ToolsKit.setRadioDrawableRight(this.pt_bt_jg, R.mipmap.jiagemoren);
        CacheKit.YouXuan.ZONG_HE = !CacheKit.YouXuan.ZONG_HE;
        CacheKit.YouXuan.XIAO_LIANG = true;
        CacheKit.YouXuan.PRICE = true;
        CacheKit.YouXuan.TIME = false;
        CacheKit.YouXuan.NOW_ORDER_BY = null;
        getFirstPtData(CacheKit.YouXuan.ZONG_HE_PAGE_SIZE, null, null);
    }

    //点击销量
    private void clickXL(boolean checked, RadioButton view, RadioButton jiage) {
        ToolsKit.setRadioDrawableRight(jiage, R.mipmap.jiagemoren);
        ToolsKit.setRadioDrawableRight(this.pt_bt_jg, R.mipmap.jiagemoren);
        CacheKit.YouXuan.XIAO_LIANG = !CacheKit.YouXuan.XIAO_LIANG;
        CacheKit.YouXuan.PRICE = true;
        CacheKit.YouXuan.TIME = false;
        CacheKit.YouXuan.ZONG_HE = false;
        JSONObject orderBy = new JSONObject();
        if (CacheKit.YouXuan.XIAO_LIANG) {
            orderBy.put("g_sales", "asc");
            CacheKit.YouXuan.NOW_ORDER_BY = orderBy;
        } else {
            orderBy.put("g_sales", "desc");
            CacheKit.YouXuan.NOW_ORDER_BY = orderBy;
        }
        getFirstPtData(CacheKit.YouXuan.XIAO_LIANG_PAGE_SIZE, null, orderBy);
    }

    //点击价格
    private void clickJG(boolean checked, RadioButton view, RadioButton jiage) {
        CacheKit.YouXuan.PRICE = !CacheKit.YouXuan.PRICE;
        CacheKit.YouXuan.XIAO_LIANG = true;
        CacheKit.YouXuan.TIME = false;
        CacheKit.YouXuan.ZONG_HE = false;
        JSONObject orderBy = new JSONObject();
        if (CacheKit.YouXuan.PRICE) {
            orderBy.put("g_price", "asc");
            // / 这一步必须要做,否则不会显示.
            ToolsKit.setRadioDrawableRight(view, R.mipmap.jiageshang);
            ToolsKit.setRadioDrawableRight(this.pt_bt_jg, R.mipmap.jiageshang);
        } else {
            ToolsKit.setRadioDrawableRight(view, R.mipmap.jiagemoren);
            ToolsKit.setRadioDrawableRight(this.pt_bt_jg, R.mipmap.jiagemoren);
            orderBy.put("g_price", "desc");
        }
        CacheKit.YouXuan.NOW_ORDER_BY = orderBy;

        getFirstPtData(CacheKit.YouXuan.PRICE_PAGE_SIZE, null, orderBy);
    }

    //点击最新
    private void clickZX(boolean checked, RadioButton view, RadioButton jiage) {
        ToolsKit.setRadioDrawableRight(jiage, R.mipmap.jiagemoren);
        ToolsKit.setRadioDrawableRight(this.pt_bt_jg, R.mipmap.jiagemoren);
        CacheKit.YouXuan.TIME = !CacheKit.YouXuan.TIME;
        CacheKit.YouXuan.XIAO_LIANG = true;
        CacheKit.YouXuan.PRICE = true;
        CacheKit.YouXuan.ZONG_HE = false;
        JSONObject orderBy = new JSONObject();
        if (CacheKit.YouXuan.TIME) {
            CacheKit.YouXuan.NOW_ORDER_BY = orderBy;
            orderBy.put("create_time", "asc");
        } else {
            CacheKit.YouXuan.NOW_ORDER_BY = orderBy;
            orderBy.put("create_time", "desc");
        }
        getFirstPtData(CacheKit.YouXuan.TIME_PAGE_SIZE, null, orderBy);
    }

    //获取第一页数据
    private void getFirstPtData(int pageSize, String isHot, JSONObject orderBy) {
        refreshLayout.finishLoadMore();
        refreshLayout.finishRefresh();
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setEnableRefresh(false);
        CacheKit.YouXuan.NOW_PAGE_NUMBER = 1;
        CacheKit.YouXuan.NOW_PAGE_LAST = false;
        JSONObject para = new JSONObject();
        para.put("pageNumber", 1);
        para.put("pageSize", pageSize);
        para.put("isHot", isHot);
        para.put("orderBy", orderBy);
        startLoading();
        new OkHttpKit().send(
                response200 -> {
                    stopLoading();
                    LogKit.E("  获取第一页数据  ---> ", response200);
                    PtResponse ptResponse = JSONObject.parseObject(response200, PtResponse.class);
                    CacheKit.YouXuan.NOW_PAGE_NUMBER = ptResponse.getPageNumber();
                    CacheKit.YouXuan.NOW_PAGE_LAST = ptResponse.isLastPage();
                    List<MultiItemEntity> list = new ArrayList<>();
                    for (MultiItemEntity e : ptResponse.getList()) {
                        list.add(e);
                    }
                    ptAdapter.setNewData(list);
                    ptAdapter.loadMoreComplete();
                    net_scro.setFocusableInTouchMode(true);
                    net_scro.scrollTo(0, srcToHeight());
                },
                error -> {
                    LogKit.E("  爆款信息---> ", error);
                }
        ).post(CONST.OPTION_PT, para, activity);
    }

    //下拉加载普通数据
    private void loadPtData() {
        JSONObject para = new JSONObject();
        LogKit.E("aaaa ---->   ", "  " + CacheKit.YouXuan.NOW_PAGE_LAST);
        if (CacheKit.YouXuan.NOW_PAGE_LAST) {
            ToastUtils.showShort("已经最后一页");
            refreshLayout.setEnableLoadMore(false);
            refreshLayout.finishLoadMore();
        } else {
            para.put("pageNumber", (CacheKit.YouXuan.NOW_PAGE_NUMBER += 1));
            para.put("pageSize", CacheKit.YouXuan.NOW_PAGE_SIZE);
            para.put("orderBy", CacheKit.YouXuan.NOW_ORDER_BY);
            avi_pt.setVisibility(View.VISIBLE);
            refreshLayout.setEnableLoadMore(false);
            refreshLayout.setEnableRefresh(false);
            new OkHttpKit().send(
                    response200 -> {
                        avi_pt.setVisibility(View.GONE);
                        LogKit.E("  下拉加载数据  ---> ", response200);
                        PtResponse ptResponse = JSONObject.parseObject(response200, PtResponse.class);
                        CacheKit.YouXuan.NOW_PAGE_NUMBER = ptResponse.getPageNumber();
                        CacheKit.YouXuan.NOW_PAGE_LAST = ptResponse.isLastPage();
                        List<MultiItemEntity> list = new ArrayList<>();
                        for (MultiItemEntity e : ptResponse.getList()) {
                            list.add(e);
                        }
                        ptAdapter.addData(list);
                        ptAdapter.loadMoreComplete();
                        refreshLayout.setEnableLoadMore(true);
                        refreshLayout.setEnableRefresh(true);
                        refreshLayout.finishLoadMore();
                        refreshLayout.finishRefresh();

                    },
                    error -> {
                        LogKit.E("error ---->   ", "  " + error);
                    }
            ).post(CONST.OPTION_PT, para, activity);
        }

    }

    //上啦刷新普通数据
    private void refrePtData() {
        refrenshLinster.refrensh(refreshLayout);
    }

    //事件监听
    public interface YouXuanLinster {
        void onClick(BaseViewHolder holder, int itemType, int position, Object item, String item_type);
    }

    private YouXuanLinster youXuanLinster;

    public void setYXLinster(YouXuanLinster youXuanLinster) {
        this.youXuanLinster = youXuanLinster;
    }

    //刷新监听
    RefrenshLinster refrenshLinster;

    public void setRefrenshLinster(RefrenshLinster refrenshLinster) {
        this.refrenshLinster = refrenshLinster;
    }

    public interface RefrenshLinster {
        void refrensh(RefreshLayout refreshLayout);
    }

    private void startLoading() {
        LogKit.E("toolbar.getHeight()   ", "  " + toolbar.getHeight());
        refreshLayout.setEnableLoadMore(false);
        ptRecl.setVisibility(View.GONE);
        avi_pt.setVisibility(View.VISIBLE);
//        baseRecl.scrollToPosition(3);
//        baseLayoutManager.scrollToPositionWithOffset(3, toolbar.getHeight());
    }

    private void stopLoading() {
        refreshLayout.setEnableLoadMore(true);
        avi_pt.setVisibility(View.GONE);
        ptRecl.setVisibility(View.VISIBLE);
    }

    public void setPt_bt_zh(RadioButton pt_bt_zh) {
        this.pt_bt_zh = pt_bt_zh;
    }

    public void setPt_bt_xl(RadioButton pt_bt_xl) {
        this.pt_bt_xl = pt_bt_xl;
    }

    public void setPt_bt_jg(RadioButton pt_bt_jg) {
        this.pt_bt_jg = pt_bt_jg;
    }

    public void setPt_bt_zx(RadioButton pt_bt_zx) {
        this.pt_bt_zx = pt_bt_zx;
    }

    public void setNet_scro(NestedScrollView net_scro) {
        this.net_scro = net_scro;
    }

    public int srcToHeight() {
        View childAt0 = baseRecl.getChildAt(0);
        View childAt1 = baseRecl.getChildAt(1);
        View childAt2 = baseRecl.getChildAt(2);
        int height = 0;
        if (childAt0 != null) {
            height += childAt0.getHeight();
        }
        if (childAt1 != null) {
            height += childAt1.getHeight();

        }
        if (childAt2 != null) {
            height += childAt2.getHeight();
        }
        return (height - toolbar.getHeight());
    }


}
